package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.transition.TransitionManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderAppealOrderInfo;
import com.chain.BrotherExchange.data.model.LegalTenderOrderDetails;
import com.chain.BrotherExchange.data.model.Payment;
import com.chain.BrotherExchange.event.CancelAppealEvent;
import com.chain.BrotherExchange.event.LegalTenderOrderChangeEvent;
import com.chain.BrotherExchange.event.SubmitAppealSuccessEvent;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateActivity;
import com.chain.BrotherExchange.ui.dialog.LookImageViewDialog;
import com.chain.BrotherExchange.ui.dialog.PaymentDialog;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.OrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.example.common.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;


/**
 * 购买法币订单详情
 */
public class LegalTenderBuyOrderDetailsActivity extends AbsNetworkStateActivity {

    @Bind(R.id.state_text) TextView mStateTextView;
    @Bind(R.id.count_down_text) TextView countDownText;
    @Bind(R.id.user_avatar_image) CircleImageView mUserAvatarImage;
    @Bind(R.id.user_name_text) TextView mUserNameTextView;
    @Bind(R.id.unit_price_text) TextView mUnitPriceTextView;
    @Bind(R.id.number_text) TextView mNumberTextView;
    @Bind(R.id.order_date_text) TextView mOrderDateTextView;
    @Bind(R.id.order_number_text) TextView mOrderNumberTextView;
    @Bind(R.id.price_text) TextView mPriceTextView;
    @Bind(R.id.price_unit_text) TextView priceUnitText;
    @Bind(R.id.payment_name_text) TextView paymentNameText;
    @Bind(R.id.switch_payment_layout) LinearLayout switchPaymentLayout;
    @Bind(R.id.payee_name_text) TextView mPayeeNameText;
    @Bind(R.id.account_name_title_text) TextView mAccountNameTitleText;
    @Bind(R.id.account_name_text) TextView mAccountNameText;
    @Bind(R.id.pay_number_title_text) TextView mPayNumberTitleText;
    @Bind(R.id.pay_number_text) TextView mPayNumberText;
    @Bind(R.id.apply_button) Button applyButton;
    @Bind(R.id.count_down_layout) LinearLayout mCountDownLayout;
    @Bind(R.id.payment_layout) View mPaymentLayout;
    @Bind(R.id.account_number_layout) View mAccountNumberLayout;
    @Bind(R.id.account_name_layout) View mAccountNameLayout;
    @Bind(R.id.root_layout) ViewGroup mRootLayout;
    @Bind(R.id.negative_button) Button mNegativeButton;

    private int mPosition;
    private String mOrderId;
    private int mAppealState, mAppealId;
    private OrderViewModel mOrderViewModel;
    private LegalTenderOrderDetails.DataBean mLegalTenderOrderDetails;

    public static void launch(Context context, String id) {
        launch(context, id, 0, 0, -1);
    }

    public static void launch(Context context, String id, int appealState, int appealId, int position) {
        context.startActivity(new Intent(context, LegalTenderBuyOrderDetailsActivity.class)
                .putExtra(C.EXTRA_ORDER_ID, id)
                .putExtra(C.EXTRA_POSITION, position)
                .putExtra(C.EXTRA_APPEAL_STATE, appealState)
                .putExtra(C.EXTRA_APPEAL_ID, appealId)
        );
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void setStatusBar() {
        ActivityBarHelper.setTransparentStatus(this);
    }

    @Override
    public int getTitleLayoutRes() {
        return R.layout.layout_screen_transparent_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_legal_currency_buy_order_details;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_order_details);
        mOrderId = getIntent().getStringExtra(C.EXTRA_ORDER_ID);
        mPosition = getIntent().getIntExtra(C.EXTRA_POSITION, -1);
        mAppealState = getIntent().getIntExtra(C.EXTRA_APPEAL_STATE, 0);
        mAppealId = getIntent().getIntExtra(C.EXTRA_APPEAL_ID, 0);
        mOrderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
        initOrderDetailsInfo();
    }

    private void initOrderDetailsInfo() {
        mOrderViewModel.legalTenderOrderDetails(mOrderId).observe(this, resource ->
                Resource.load(this, resource, this, this::ontoOrderDetailsToView)
        );
    }

    private void ontoOrderDetailsToView(LegalTenderOrderDetails.DataBean result) {
        this.mLegalTenderOrderDetails = result;
        mUserAvatarImage.setImageResource(R.drawable.ic_placeholder_avatars);
        mUserNameTextView.setText(result.getSell_name()); // 用户昵称
        mUnitPriceTextView.setText(result.getPriceText() + "CNY"); // 单价
        mPriceTextView.setText(result.getTotalPrice()); // 价格
        mOrderDateTextView.setText(result.getBegin_time()); // 下单时间
        mNumberTextView.setText(result.getNumText() + result.getToken_name()); // 数量
        mOrderNumberTextView.setText(result.getOrder_id()); // 订单号
        loadOrderState(result.getStatus()); // 加载订单状态
        loadPaymentOntoView(result);
    }

    private void loadPaymentOntoView(LegalTenderOrderDetails.DataBean result) {
        List<Payment> payments = new ArrayList<>();
        if (!TextUtils.isEmpty(result.getBank_info())) {
            payments.add(new Payment(1, getString(R.string.bank_card), result.getBankpay_name(),
                    result.getCard_num(), result.getBank_info(), null));
        }

        if (!TextUtils.isEmpty(result.getAlipay_name())) {
            payments.add(new Payment(2, getString(R.string.ali_pay), result.getAlipay_name(),
                    result.getAlipay(), null, result.getAli_receipt_code()));
        }

        if (!TextUtils.isEmpty(result.getWechat_name())) {
            payments.add(new Payment(3, getString(R.string.we_chat_pay), result.getWechat_name(),
                    result.getWechat(), null, result.getWechat_receipt_code()));
        }

        if (!TextUtils.isEmpty(result.getPaypal_num())) {
            payments.add(new Payment(4, "PayPal", null,
                    result.getPaypal_num(), null, null));
        }

        loadPaymentView(payments.get(0));

        // 选择支付方式
        switchPaymentLayout.setOnClickListener(v -> PaymentDialog.show(
                this, payments, this::loadPaymentView));
    }

    private void loadPaymentView(Payment payment) {
        switch (payment.getType()) {
            case 1:
                displayBankPayment(payment);
                break;
            case 2:
                displayAliPayPayment(payment);
                break;
            case 3:
                displayWeChatPayment(payment);
                break;
            case 4:
                displayPayPalPayment(payment);
                break;
        }
    }

    private void loadOrderState(int orderState) {
        switch (orderState) {
            case 1:
                waitingPaymentState();
                break;
            case 2:
                toBeReleasedState();
                break;
            case 3:
                completeTransactionState();
                break;
            case 4:
                canceledState();
                break;
        }
    }

    // 待支付
    private void waitingPaymentState() {
        mStateTextView.setText(getString(R.string.order_state_unpaid));
        int id = Integer.parseInt(mOrderId);

        // 支付
        applyButton.setOnClickListener(v -> {
            mOrderViewModel.confirmPayment(id).observe(this, resource -> {
                if (resource.state == Resource.Status.LOADING) {
                    applyButton.setEnabled(false);
                } else {
                    Androids.makeText(resource.message);
                    if (resource.state == Resource.Status.SUCCESS) {
                        TransitionManager.beginDelayedTransition(mRootLayout);
                        loadOrderState(2); // 设置为待放行状态
                        EventBus.getDefault().post(new LegalTenderOrderChangeEvent(mPosition, 2));
                    }
                }
            });
        });

        // 取消订单
        cancelOrder();
    }

    // 待放行
    private void toBeReleasedState() {
        mStateTextView.setText(getString(R.string.order_state_to_be_released)); // 订单状态
        mCountDownLayout.setVisibility(View.GONE);
        mPaymentLayout.setVisibility(View.GONE);

        applyButton.setVisibility(mAppealState <= 0 ? View.VISIBLE : View.GONE);
        applyButton.setText(getString(R.string.appeal_immediately));
        applyButton.setOnClickListener(v -> {
            String token_name = mLegalTenderOrderDetails.getToken_name();
            String order_id = mLegalTenderOrderDetails.getOrder_id();
            LegalTenderAppealActivity.launch(v.getContext(), new LegalTenderAppealOrderInfo(
                    token_name, order_id, 1, mLegalTenderOrderDetails.getToken_id()
            ), mPosition);
        });

        if (mAppealState != 1) {
            cancelOrder();
        } else {
            mNegativeButton.setText(getString(R.string.cancel_appeal));
            mNegativeButton.setOnClickListener(v ->
                    mOrderViewModel.cancelAppeal(mAppealId)
                            .observe(this, resource -> {
                                if (resource.state == Resource.Status.LOADING) {
                                    mNegativeButton.setEnabled(false);
                                } else {
                                    Androids.makeText(resource.message);
                                    if (resource.state == Resource.Status.SUCCESS) {
                                        TransitionManager.beginDelayedTransition(mRootLayout);
                                        mAppealState = 4; // 取消申诉
                                        toBeReleasedState();
                                        EventBus.getDefault().post(new CancelAppealEvent());
                                    }
                                }
                            })
            );
        }
    }

    private void cancelOrder() {
        mNegativeButton.setText(R.string.cancel_order);
        mNegativeButton.setOnClickListener(v -> {
            new AlertDialog.Builder(this).setTitle(getString(R.string.cancel_order))
                    .setMessage(R.string.are_you_sure_you_want_to_cancel_egal_currency_order)
                    .setPositiveButton(R.string.sure, (dialog, which) ->
                            mOrderViewModel.cancelLegalTenderOrder(Integer.parseInt(mOrderId), 2)
                                    .observe(LegalTenderBuyOrderDetailsActivity.this, resource -> {
                                        if (resource.state == Resource.Status.LOADING) {
                                            mNegativeButton.setEnabled(false);
                                        } else {
                                            Androids.makeText(resource.message);
                                            if (resource.state == Resource.Status.SUCCESS) {
                                                TransitionManager.beginDelayedTransition(mRootLayout);
                                                loadOrderState(4); // 设置为待放行状态
                                                EventBus.getDefault().post(new LegalTenderOrderChangeEvent(mPosition, 4));
                                            }
                                        }
                                    })).setNegativeButton(R.string.let_me_think_again, (dialog, which) -> dialog.dismiss()).show();

        });
    }

    // 交易完成
    private void completeTransactionState() {
        mStateTextView.setText(R.string.complete); // 订单状态
        mCountDownLayout.setVisibility(View.GONE);
        mPaymentLayout.setVisibility(View.GONE);
        applyButton.setVisibility(View.GONE);
        mNegativeButton.setVisibility(View.GONE);
    }

    // 已取消
    private void canceledState() {
        mStateTextView.setText(R.string.order_state_canceled);
        mCountDownLayout.setVisibility(View.GONE);
        mPaymentLayout.setVisibility(View.GONE);
        applyButton.setVisibility(View.GONE);
        mNegativeButton.setVisibility(View.GONE);
    }

    // 银行卡付款
    private void displayBankPayment(Payment payment) {
        mAccountNameTitleText.setText(R.string.belongs_bank);
        paymentNameText.setText(R.string.bank_card);
        mPayNumberTitleText.setText(R.string.bank_card_number);
        mPayeeNameText.setText(payment.getCreditedAccount()); // 收款人
        mAccountNameText.setText(payment.getAddress()); // 银行名称
        mPayNumberText.setText(payment.getCreditedNumber()); // 银行卡号
        mAccountNameLayout.setVisibility(View.VISIBLE);
        mAccountNumberLayout.setVisibility(View.VISIBLE);
        mPayNumberText.setOnClickListener(null);

        // 复制银行卡号
        mPayNumberText.setOnClickListener(v ->
                Androids.copyToChipBoard(this, payment.getCreditedNumber()));
    }

    // 支付宝付款
    private void displayAliPayPayment(Payment payment) {
        mAccountNameTitleText.setText(R.string.ali_pay_account);
        paymentNameText.setText(R.string.ali_pay);
        mPayeeNameText.setText(payment.getCreditedAccount()); //用户名
        mAccountNameText.setText(payment.getCreditedNumber()); // 账号
        mPayNumberTitleText.setText(R.string.payment_code);
        mPayNumberText.setText(R.string.look_payment_code);
        mAccountNameLayout.setVisibility(View.VISIBLE);
        mAccountNumberLayout.setVisibility(View.VISIBLE);
        mPayNumberText.setOnClickListener(v -> LookImageViewDialog.show(this, payment.getCodePath()));
    }

    // 微信付款
    private void displayWeChatPayment(Payment payment) {
        mAccountNameTitleText.setText(R.string.we_chat_account);
        paymentNameText.setText(R.string.we_chat_pay);
        mPayeeNameText.setText(payment.getCreditedAccount()); //用户名
        mAccountNameText.setText(payment.getCreditedNumber()); // 账号
        mPayNumberTitleText.setText(R.string.payment_code);
        mPayNumberText.setText(R.string.look_payment_code);
        mAccountNameLayout.setVisibility(View.VISIBLE);
        mAccountNumberLayout.setVisibility(View.VISIBLE);
        mPayNumberText.setOnClickListener(v -> LookImageViewDialog.show(this, payment.getCodePath()));
    }

    // payPal付款
    private void displayPayPalPayment(Payment payment) {
        paymentNameText.setText(R.string.pay_pal);
        mAccountNameTitleText.setText(R.string.pay_pal_account);
        mAccountNameText.setText(payment.getCreditedNumber()); // 账号
        mAccountNameLayout.setVisibility(View.GONE);
        mAccountNumberLayout.setVisibility(View.GONE);
    }

    @Subscribe
    public void submitAppealSuccessEvent(SubmitAppealSuccessEvent event) {
        mAppealState = 1;
        mAppealId = event.id;
        toBeReleasedState();
    }

    @Override
    public void onAnewRequest() {
        initOrderDetailsInfo();
    }
}
